package com.zyl.javabasic.ThreadLocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zyl
 * @Description
 * @since 2025/6/23 20:53
 */
public class UserContextHolder {
    // 存储用户信息的ThreadLocal
    private static final ThreadLocal<User> userContext = new ThreadLocal<>();

    public static void setUser(User user) {
        userContext.set(user);
    }

    public static User getUser() {
        return userContext.get();
    }

    public static void clear() {
        userContext.remove();
    }

    // 模拟用户类
    static class User {
        String id;
        String name;

        public User(String id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" + "id='" + id + '\'' + ", name='" + name + '\'' + '}';
        }
    }

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // 模拟5个请求
        for (int i = 1; i <= 5; i++) {
            final int userId = i;
            executor.execute(() -> {
                try {
                    // 设置用户信息
                    User user = new User("UID-" + userId, "User-" + userId);
                    UserContextHolder.setUser(user);

                    // 业务处理(可以跨多层方法调用)
                    doBusiness();
                } finally {
                    // 清理
                    UserContextHolder.clear();
                }
            });
        }

        executor.shutdown();
    }

    private static void doBusiness() {
        // 在任何地方都可以获取用户信息，无需传递参数
        User user = UserContextHolder.getUser();
        System.out.println(Thread.currentThread().getName() + " 处理用户: " + user);
    }
}
